import React, { useCallback, useEffect, useState, useRef, useMemo } from "react";
import { message, Modal } from "antd";
import { outBoundOrderManualDelivery, exportOutbound, isManualDelivery } from "./service";
import { downLoad } from "@/utils/utils";
import { getCurrentUser } from "@/utils/authority";
import { WAIT_SHIP } from "@/views/utils/constant";
export default ({ getFormData }) => {
	const [visibleDialogName, setVisibleDialogName] = useState("");
	const [customDialogProps, setCustomDialogProps] = useState({});
	const clearDialog = () => {
		setVisibleDialogName("");
		setCustomDialogProps({});
	};
	const dateFormat = "YYYY-MM-DD HH:mm:ss";

	//处理搜索数据
	const resetFormData = (API_DATA, type) => {
		// 收件人信息相关
		setSearchData(API_DATA, "consigneeKey", "consigneeVal");
		// 备注相关
		setSearchData(API_DATA, "remarkKey", "remarkVal");
		// // 时间类型相关
		// setSearchData(API_DATA, "timeKey", "timeVal");
		const KEYS = ["outboundNo", "systemNo", "shopOrderNo"];
		// 逗号分割转换数组
		KEYS.forEach(key => {
			if (typeof API_DATA[key] === "string") API_DATA[key] = API_DATA[key]?.split(",");
		});
		// 解决调用列表接口Tab状态不一致，不能用type
		API_DATA["outboundStatus"] = type;
		// 排序参数
		// 标签
		const flagMap = {
			true: 1,
			false: 2
		};
		API_DATA["orderLabelFlag"] = flagMap[API_DATA?.orderLabelIdList?.isLabelOr];
		API_DATA["orderLabelIdList"] = API_DATA?.orderLabelIdList?.containLabelIdArr || null;
		function setSearchData(data, key, value) {
			if (data[key] === undefined) return;
			data[data[key]] = data[value];
			delete data[key];
			delete data[value];
		}
		return API_DATA;
	}

	const handleCommand = async (TEXT, data, callback) => {

		const { searchForm, key, selectedRows, type } = data;

		switch (TEXT) {
			case "修改订单备注":
				setCustomDialogProps({
					data,
					callback
				});
				setVisibleDialogName("OrderRemarksModal");
				break;
			case "手动发货":
				if (key == 1 && !selectedRows.length) {
					message.warning("请勾选订单数据");
					return;
				}
				const deliverParams = {
					type: key
				};
				if(key == 1) {//针对选中
					deliverParams.outboundNos = selectedRows.map(e => e.outboundNo);
				} else {
					const val = resetFormData(searchForm.getFieldsValue(), type)
					deliverParams.outboundOrderListQueryVO = val;
				}
				// 获取可发货订单数量，如果是0，提示： 没有可操作的数据，请重新勾选
				const res = await isManualDelivery(deliverParams);
				if (res.success) {
					setCustomDialogProps({
						deliveryData: res.data
					});
					setVisibleDialogName("ManualShipmentModal");
				} else {
					return message.warning("获取可发货订单数量失败");
				}
				break;
			case "手动发货确定后":
				{
					const { outboundNos, fetchList, formData } = data;
					outBoundOrderManualDelivery({
						actualWeight: formData.actualWeight,
						force: formData.force ? true : false,
						readEstimatedWeight: formData.readEstimatedWeight ? 1 : 0,
						outboundNos: outboundNos,
						deliveryScenario: 6
					})
						.then(res => {
							const { success, data, msg } = res;
							if (success) {
								Modal.info({
									title: '发货提示',
									content: (
										<div>
											<p>成功数：<span className="common-color10">{data.okSystemList.length}</span>，失败数：<span className="common-color9">{data.errorSystemList.length}</span></p>
											{data.errorMsgList.length > 0 && <p>失败原因可能是:{data.errorMsgList.join()},<br/>具体请看每个订单的订单日志</p>}
											<p></p>
										</div>
									),
									onOk() {
										setCustomDialogProps({});
										setVisibleDialogName();
										fetchList();
									},
								});
							} else {
								message.warn("操作失败");
							}
						})
						.catch(err => {
							console.log(err);
						})
						.finally(() => {});
				}

				break;
			case "合格证批量打印":
				if (!selectedRows.length) {
					message.warning("请勾选订单数据");
					return;
				}
				setCustomDialogProps({});
				setVisibleDialogName("CertificatePrintModal");
				break;
			case "快递批量打印":
				if (!selectedRows.length) {
					message.warning("请勾选订单数据");
					return;
				}
				// 需要把没有物流单号的数据剔除掉 waybillNo
				if (selectedRows.length === 1 && !selectedRows[0].waybillNo) {
					message.warning("该订单没有物流单号");
					return;
				}
				// 勾选多条都是物流单号为空
				if (selectedRows.filter(e => e.waybillNo).length === 0) {
					message.warning("没有可以打印的出库单");
					return;
				}
				setCustomDialogProps({
					fetchList: data.fetchList,
					selectedRows: selectedRows.filter(e => e.waybillNo),
					len: selectedRows?.length
				});
				setVisibleDialogName("ExpressPrintModal");
				break;
			case "导出":
				const createTaskData = {
					taskType: 4001
				};
				const searchData = getFormData();
				const params = {
					businessKey: "",
					// current: pagination.current,
					// size: pagination.pageSize,
					uuid: getCurrentUser().uuid,
					queryJson: JSON.stringify({
						outboundStatus: searchData.outboundStatus
					})
				};
				if (key === "导出所有项") {
					params.businessKey = 1;
				}
				if (key === "导出筛选项") {
					params.businessKey = 2;
					// 导出筛选项json
					params.queryJson = JSON.stringify(searchData);
				}
				if (key === "导出勾选项") {
					if (!selectedRows.length) {
						message.warning("请勾选订单数据");
						return;
					}
					params.businessKey = 3;
					// 勾选的出库单号
					params.outboundNos = selectedRows.map(e => e.outboundNo);
				}
				createTaskData.businessParam = JSON.stringify(params);
				setCustomDialogProps({ createTaskData });
				setVisibleDialogName("ActionExportExcelModal");
				break;
			default:
				break;
		}
	};

	return { handleCommand, clearDialog, visibleDialogName, setVisibleDialogName, customDialogProps, setCustomDialogProps };
};
